package io.gitee.minelx.commontools.encrypt.cipher;

import io.gitee.minelx.commontools.encrypt.cipher.algorithm.Algorithm;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import java.security.NoSuchAlgorithmException;

public class CipherPattern {

	private final String algorithm;

	private final String strategy;

	private final String padding;

	private CipherPattern(String algorithm, String strategy, String padding) {
		this.algorithm = algorithm;
		this.strategy = strategy;
		this.padding = padding;
	}

	public CipherFactory password(String password) {
		return new Password(
				this,
				algorithm().secretKey(password));
	}

	public CipherFactory passwordAndIV(String password, String ivPassword) {
		return new PasswordWithIV(
				this,
				algorithm().secretKey(password),
				new IvParameterSpec(ivPassword.getBytes()));
	}

	public Cipher obtainCipher() {
		try {
			return Cipher.getInstance(pattern());
		} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
			throw new IllegalArgumentException("wrong pattern: " + pattern(), e);
		}
	}

	public Algorithm algorithm() {
		return Algorithm.from(algorithm);
	}

	public String pattern() {
		return algorithm + "/" + strategy + "/" + padding;
	}

	public static CipherPattern of(String algorithm, String strategy, String padding) {
		return new CipherPattern(algorithm, strategy, padding);
	}

	public static CipherPattern from(String pattern) {
		String[] segments = pattern.split("/");
		return new CipherPattern(segments[0], segments[1], segments[2]);
	}
}
